(五)Vue 状态管理—— Vuex

什么是 Vuex?

  Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式

  Vuex 采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。

  状态管理集中式存储管理到底是什么呢?
  简单来讲,就是创建一个单例对象来集中管理多个组件共享的变量,然后将这个对象放置在顶层的 Vue 实例中,使得其他组件可以共享这个对象的所有变量属性。

  而 Vuex 就是提供这种功能的一个插件!它也集成到 Vue 的官方调试工具 devtools extension,提供了诸如零配置的 time-travel 调试、状态快照导入导出等高级调试功能。
  复杂点来说,举个栗子:从一个简单的 Vue 计数应用开始:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
new Vue({
// state
data () {
return {
count: 0
}
},
// view
template: `
<div>{{ count }}</div>
`,
// actions
methods: {
increment () {
this.count++
}
}
})

  这个状态自管理应用包含以下几个部分:

  • state,驱动应用的数据源;
  • view,以声明方式将 state 映射到视图;
  • actions,响应在 view 上的用户输入导致的状态变化。

  以下是一个表示“单向数据流”理念的简单示意:

  但是,当我们的应用遇到多个组件共享状态时,单向数据流的简洁性很容易被破坏:

  • 多个视图依赖于同一状态。
  • 来自不同视图的行为需要变更同一状态。

  对于问题一,传参的方法对于多层嵌套的组件将会非常繁琐,并且对于兄弟组件间的状态传递无能为力。
  对于问题二,我们经常会采用父子组件直接引用或者通过事件来变更和同步状态的多份拷贝。

  以上的这些模式非常脆弱,通常会导致代码难以维护。

  因此,我们为什么不把组件的共享状态抽取出来,以一个全局单例模式来管理呢?

  在该模式下,组件树将构成了一个巨大的“视图”,不管在树的哪个位置,任何组件都能获取状态或者触发行为!

  这样,通过定义和隔离状态管理中的各种概念并通过强制规则维持视图和状态间的独立性,代码将会变得更结构化且易维护。

  这就是 Vuex 背后的基本思想,借鉴了 FluxReduxThe Elm Architecture
  但与其他模式不同的是,Vuex 是专门为 Vue.js 设计的状态管理库,以利用 Vue.js 的细粒度数据响应机制来进行高效的状态更新。

Vuex 的应用场景

  思考一下,有什么状态需要我们在多个组件间共享的呢?
  一般在实际开发中,以下信息需要被多个组件共享:

  • 用户的相关信息(token、登录状态、用户名、用户头像、用户位置等等)
  • 商品的购物车

  这些状态信息,都可以放置 Vuex 中,对它们进行保存和管理,且其还是响应式的呢!

Vuex 的安装与使用

  我们可以在创建项目时安装 Vuex,也可在创建项目后使用如下命令安装:

1
npm install vuex --save

  Vuex 的使用类似 Vue Router,为了标准化工程,一般在src/store文件夹创建index.js文件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
}
})

export default store

  一般而言,我们使用的都是 Vuex 的 Store 实例。

Vuex 的核心

  Vuex 的 Store 实例包涵以下 5 个核心概念( Vuex Store 实例的 5 个属性):

  • State:单一状态树
  • Getter:类似于计算属性
  • Mutation:状态修改
  • Action:异步操作
  • Module:多模块 Store


  如上图所示:Vuex 并不推荐组件直接修改State中的变量,而是要求你先通过 Dispatch操作Actions,再由Actions提交(Commit)到 Mutations中,最后让Mutations来修改State中的变量。
  简而言之,要想修改State中的变量,必须通过Mutations来修改。
  若修改时有异步操作,需先通过Actions进行操作,若无则可跳过Actions
  虽然操作起来变得非常繁杂,但是这么做的目的是Devtools插件来记录State的变量状态,可便于跟踪与调试

State ——单一状态树

  Vuex 使用单一状态树(亦称唯一数据源(SSOT))——即用一个对象就包含了全部的应用层级状态。
  这意味着,每个应用将仅仅包含一个 store 实例。
  单一状态树让我们能够直接地定位任一特定的状态片段,在调试的过程中也能轻易地取得整个当前应用状态的快照。
  存储在 Vuex 中的数据和 Vue 实例中的 data 遵循相同的规则。

在 Vue 组件中获得 Vuex 状态

  那么我们如何在 Vue 组件中展示状态呢?
  Vuex 通过 store 选项,提供了一种机制将状态从根组件“注入”到每一个子组件中:

1
2
3
4
5
6
7
8
9
10
11
12
13
import store from "./store";

const app = new Vue({
el: '#app',
// 把 store 对象提供给 “store” 选项,这可以把 store 的实例注入所有的子组件
store,
components: { Counter },
template: `
<div class="app">
<counter></counter>
</div>
`
})

  通过在根实例中注册 store 选项,该 store 实例会注入到根组件下的所有子组件中,且子组件能通过 this.$store 访问到。
  让我们更新下 Counter 的实现:

1
2
3
4
5
6
7
8
const Counter = {
template: `<div>{{ count }}</div>`,
computed: {
count () {
return this.$store.state.count
}
}
}

Getter ——计算属性

  有时候我们需要从 store 中的 state 中派生出一些状态,例如对列表进行过滤并计数:

1
2
3
4
5
computed: {
doneTodosCount () {
return this.$store.state.todos.filter(todo => todo.done).length
}
}

  若有多个组件需要用到此属性,我们要么复制这个函数要么抽取到一个共享函数然后在多处导入它。
  但你会发现——无论使用哪种方式都不是很理想。

  Vuex 允许我们在 store 中定义“getter”(这可以认为是 store 的计算属性)。
  就像计算属性一样,getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算。

  Getter 接受 state 作为其第一个参数:

1
2
3
4
5
6
7
8
9
10
11
12
13
const store = new Vuex.Store({
state: {
todos: [
{ id: 1, text: '...', done: true },
{ id: 2, text: '...', done: false }
]
},
getters: {
doneTodos: state => {
return state.todos.filter(todo => todo.done)
}
}
})

通过属性访问

  Getter 会暴露为 store.getters 对象,你可以以属性的形式访问这些值:

1
store.getters.doneTodos // -> [{ id: 1, text: '...', done: true }]

  Getter 也可以接受其他 getter 作为第二个参数:

1
2
3
4
5
6
7
8
9
10
11
getters: {
doneTodos: state => {
return state.todos.filter(todo => todo.done)
}
// 接受其他 getter 作为第二个参数
doneTodosCount: (state, getters) => {
return getters.doneTodos.length
}
}

store.getters.doneTodosCount // -> 1

  我们可以很容易地在任何组件中使用它:

1
2
3
4
5
computed: {
doneTodosCount () {
return this.$store.getters.doneTodosCount
}
}

注意哦:getter 在通过属性访问时是作为 Vue 的响应式系统的一部分缓存其中的。

通过方法访问

  你也可以通过让 getter 返回一个函数,来实现给 getter 传参。这在对 store 里的数组进行查询时非常有用。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
getters: {
// ...
getTodoById: (state) => (id) => {
return state.todos.find(todo => todo.id === id)
}
// 上面的相当于
getTodoById: state => {
return id => {
return state.todos.find(todo => todo.id === id)
}
}
//
getTodoById: state => {
return function (id) => {
return state.todos.find(todo => todo.id === id)
}
}
}
store.getters.getTodoById(2) // -> { id: 2, text: '...', done: false }

注意哦:getter 在通过方法访问时,每次都会去进行调用,而不会缓存结果。

mapGetters 辅助函数

  mapGetters 辅助函数仅仅是将 store 中的 getter 映射到局部计算属性:

1
2
3
4
5
6
7
8
9
10
11
12
13
import { mapGetters } from 'vuex'

export default {
// ...
computed: {
// 使用对象展开运算符将 getter 混入 computed 对象中
...mapGetters([
'doneTodosCount',
'anotherGetter',
// ...
])
}
}

  如果你想将一个 getter 属性另取一个名字,使用对象形式:

1
2
3
4
mapGetters({
// 把 `this.doneCount` 映射为 `this.$store.getters.doneTodosCount`
doneCount: 'doneTodosCount'
})

Mutation

  前面说过,更改 Vuex store 中状态变量的唯一方法是提交 mutation
  mutation 非常类似于事件,其由 2 部分组成:

  • 一个字符串的 事件类型(type)
  • 一个 回调函数(handler)

  回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数:

1
2
3
4
5
6
7
8
9
10
11
const store = new Vuex.Store({
state: {
count: 1
},
mutations: {
increment (state) {
// 变更状态
state.count++
}
}
})

  这个选项更像是事件注册:“当触发一个类型为 increment 的 mutation 时,调用此函数。”
  若要唤醒一个 mutation handler,是不能直接调用的,而需要以相应的 type 调用 以下方法:

1
store.commit('increment')

提交载荷(Payload)

  可以向 store.commit 传入额外的参数,其被称为载荷(payload)

1
2
3
4
5
6
7
// ...
mutations: {
increment (state, n) {
state.count += n
}
}
store.commit('increment', 10)

  在大多数情况下,载荷应该是一个对象,这样可以包含多个字段并且记录的 mutation 会更易读:

1
2
3
4
5
6
7
8
9
// ...
mutations: {
increment (state, payload) {
state.count += payload.amount
}
}
store.commit('increment', {
amount: 10
})

对象风格的提交方式

  提交 mutation 的另一种方式是直接使用包含 type 属性的对象:

1
2
3
4
store.commit({
type: 'increment',
amount: 10
})

  当使用对象风格的提交方式,整个对象都作为载荷传给 mutation 函数,因此 handler 保持不变:

1
2
3
4
5
mutations: {
increment (state, payload) {
state.count += payload.amount
}
}

在组件中提交 Mutation(了解)

  你可以在组件中使用 this.$store.commit('xxx') 提交 mutation,或者使用 mapMutations 辅助函数将组件中的 methods 映射为 store.commit 调用(需要在根节点注入 store)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import { mapMutations } from 'vuex'

export default {
// ...
methods: {
...mapMutations([
'increment', // 将 `this.increment()` 映射为 `this.$store.commit('increment')`

// `mapMutations` 也支持载荷:
'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.commit('incrementBy', amount)`
]),
...mapMutations({
add: 'increment' // 将 `this.add()` 映射为 `this.$store.commit('increment')`
})
}
}

注意点

  Mutation 的使用需要注意以下几点:

  • Mutation 必须是同步函数,这样状态变量才能被 Devtools 跟踪
  • 由于mutation 都是同步事务,处理异步操作可以使用 Action
  • 由于 store 的状态是响应式的,最好提前在 store 中初始化好所有所需属性(后续添加请使用Vue.set
  • 最好使用常量替代 Mutation 事件类型,代码更友好哦:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    // mutation-types.js
    export const SOME_MUTATION = 'SOME_MUTATION'
    // store.js
    import Vuex from 'vuex'
    import { SOME_MUTATION } from './mutation-types'

    const store = new Vuex.Store({
    state: { ... },
    mutations: {
    // 我们可以使用 ES2015 风格的计算属性命名功能来使用一个常量作为函数名
    [SOME_MUTATION] (state) {
    // mutate state
    }
    }
    })

Action

  Action 类似于 mutation,但不同的是:

  • Action 提交的是 mutation,而不是直接变更状态
  • Action 可以包含任意异步操作

  下面让我们来注册一个简单的 action:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
},
actions: {
increment (context) {
context.commit('increment')
}
}
})

  Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象,因此你可以调用 context.commit 提交一个 mutation,或者通过 context.statecontext.getters 来获取 state 和 getters。
  当我们在之后介绍到 Modules 时,你就知道 context 对象为什么不是 store 实例本身了。

  实践中,我们会经常用到 ES2015 的 参数解构 来简化代码(特别是我们需要调用 commit 很多次的时候):

1
2
3
4
5
actions: {
increment ({ commit }) {
commit('increment')
}
}

分发 Action

  Action 通过 store.dispatch 方法触发:

1
store.dispatch('increment')

  乍一眼看上去感觉多此一举,我们直接分发 mutation 岂不更方便?
  实际上并非如此,还记得 mutation 必须同步执行这个限制么?
  Action 就不受约束!因此我们可以在 action 内部执行异步操作:

1
2
3
4
5
6
7
actions: {
incrementAsync ({ commit }) {
setTimeout(() => {
commit('increment')
}, 1000)
}
}

  Actions 支持同样的载荷方式和对象方式进行分发:

1
2
3
4
5
6
7
8
9
10
// 以载荷形式分发
store.dispatch('incrementAsync', {
amount: 10
})

// 以对象形式分发
store.dispatch({
type: 'incrementAsync',
amount: 10
})

  来看一个更加实际的购物车示例,涉及到调用异步 API分发多重 mutation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
actions: {
checkout ({ commit, state }, products) {
// 把当前购物车的物品备份起来
const savedCartItems = [...state.cart.added]
// 发出结账请求,然后乐观地清空购物车
commit(types.CHECKOUT_REQUEST)
// 购物 API 接受一个成功回调和一个失败回调
shop.buyProducts(
products,
// 成功操作
() => commit(types.CHECKOUT_SUCCESS),
// 失败操作
() => commit(types.CHECKOUT_FAILURE, savedCartItems)
)
}
}

  注意我们正在进行一系列的异步操作,并且通过提交 mutation 来记录 action 产生的副作用(即状态变更)。

在组件中分发 Action

  在组件中使用 this.$store.dispatch('xxx') 分发 action,或者使用 mapActions 辅助函数将组件的 methods 映射为 store.dispatch 调用(需要先在根节点注入 store):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import { mapActions } from 'vuex'

export default {
// ...
methods: {
...mapActions([
'increment', // 将 `this.increment()` 映射为 `this.$store.dispatch('increment')`

// `mapActions` 也支持载荷:
'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.dispatch('incrementBy', amount)`
]),
...mapActions({
add: 'increment' // 将 `this.add()` 映射为 `this.$store.dispatch('increment')`
})
}
}

组合 Action

  Action 通常是异步的,那么如何知道 action 什么时候结束呢?
  更重要的是,我们如何才能组合多个 action,以处理更加复杂的异步流程?

  首先,你需要明白 store.dispatch 可以处理被触发的 action 的处理函数返回的 Promise,并且 store.dispatch 仍旧返回 Promise:

1
2
3
4
5
6
7
8
9
10
actions: {
actionA ({ commit }) {
return new Promise((resolve, reject) => {
setTimeout(() => {
commit('someMutation')
resolve()
}, 1000)
})
}
}

  现在你可以:

1
2
3
store.dispatch('actionA').then(() => {
// ...
})

  在另外一个 action 中也可以:

1
2
3
4
5
6
7
8
actions: {
// ...
actionB ({ dispatch, commit }) {
return dispatch('actionA').then(() => {
commit('someOtherMutation')
})
}
}

  最后,如果我们利用 async / await,我们可以如下组合 action:

1
2
3
4
5
6
7
8
9
10
11
// 假设 getData() 和 getOtherData() 返回的是 Promise

actions: {
async actionA ({ commit }) {
commit('gotData', await getData())
},
async actionB ({ dispatch, commit }) {
await dispatch('actionA') // 等待 actionA 完成
commit('gotOtherData', await getOtherData())
}
}

  一个 store.dispatch 在不同模块中可以触发多个 action 函数。
  在这种情况下,只有当所有触发函数完成后,返回的 Promise 才会执行。

Module

  由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。
  因此,当应用变得非常复杂时,store 对象就有可能变得相当臃肿。

  为了解决以上问题,Vuex 允许我们将 store 分割成模块(module)

  每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
const moduleA = {
state: { ... },
mutations: { ... },
actions: { ... },
getters: { ... }
}

const moduleB = {
state: { ... },
mutations: { ... },
actions: { ... }
}

const store = new Vuex.Store({
modules: {
a: moduleA,
b: moduleB
}
})

store.state.a // -> moduleA 的状态
store.state.b // -> moduleB 的状态

  默认情况下,模块内部的 action、mutation 和 getter 是注册在全局命名空间的——这样使得多个模块能够对同一 mutation 或 action 作出响应。

模块的局部状态

  对于模块内部的 mutation 和 getter,接收的第一个参数是模块的局部状态对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const moduleA = {
state: { count: 0 },
mutations: {
increment (state) {
// 这里的 `state` 对象是模块的局部状态
state.count++
}
},

getters: {
doubleCount (state) {
return state.count * 2
}
}
}

  同样,对于模块内部的 action,局部状态通过 context.state 暴露出来,根节点状态则为 context.rootState

1
2
3
4
5
6
7
8
9
10
const moduleA = {
// ...
actions: {
incrementIfOddOnRootSum ({ state, commit, rootState }) {
if ((state.count + rootState.count) % 2 === 1) {
commit('increment')
}
}
}
}

  对于模块内部的 getter,根节点状态会作为第三个参数暴露出来:

1
2
3
4
5
6
7
8
const moduleA = {
// ...
getters: {
sumWithRootCount (state, getters, rootState) {
return state.count + rootState.count
}
}
}

Vue 的目录结构

  当 Vuex 帮助我们管理的内容过多时,好的目录结构使得代码更加清晰,下面为优雅的src目录:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
├── assets
├── api
│ └── ... # 抽取出 API 请求
├── common # 存放公共的 js 文件(如常量)
│  ├── const.js
│  ├── utils.js
├── components
│  ├── common # 存放公共组件
│  └── content # 业务相关组件(针对当前项目)
├── network # 网络相关
├── router
│ ├── index.js
├── store
│ ├── index.js # 我们组装模块并导出 store 的地方
│ ├── actions.js # 根级别的 actions
│ ├── mutations.js # 根级别的 mutations
│ └── modules
│ ├── cart.js # 购物车模块
│ └── products.js # 产品模块
├── views
│ └── Home.vue
├── App.vue
└── main.js

参考

0%